/*
 * @Author: gk 
 *  平台更新
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: csy
 * @Last Modified time: 2019-05-27 16:52:55
 */
layui.config({
}).use(['element', 'zlConfig', 'zlContext', 'table', 'layer', 'zlSelectEx', 'form', 'zlPinYin', 'upload'], function (exports) {
	var $ = layui.$
		, zlContext = layui.zlContext
		, layer = layui.layer
		, table = layui.table
		, form = layui.form
		, upload = layui.upload
		, zlPinYin = layui.zlPinYin
		, zlConfig = layui.zlConfig
		, statusName = zlConfig.global.result.statusName
		, msgName = zlConfig.global.result.msgName
		, dataName = zlConfig.global.result.dataName
		, OK = zlConfig.global.result.okState
		, fullheight = 'full-30'
		, customCurr = 1
		, loadingLayer
		, intervalId = undefined;
	var fromlayerIndex,
		updateProcessTimer,
		// processLayerIndex,
		isloadsearch = false,
		isPrvFinish = true;

	//渲染版本更新信息列表
	var versionTb = table.render({
		elem: '#tbVersion'
		, sortload: true
		, height: fullheight
		, response: zlConfig.global.gridResponse
		, url: layui.cache['contentPath'] + '/manager/version/query'
		, method: 'post'
		, updId: '45E52063E67A49E989CF158504E844B9'
		, toolbar: "#toolbarVersion"
		, defaultToolbar: ['filter']
		, limit: 20
		, limits: [20, 50, 100, 200, 500, 1000]
		, page: true
		, cols: [[ //表头
			{ type: 'numbers', fixed: 'left', title: '#' }
			, { type: 'checkbox', fixed: 'left' }
			, { field: 'VER_SUOSXT', title: '所属系统', sort: true, width: 150 }
			, { field: 'VER_BANB', title: '版本', sort: true, width: 150 }
			, { field: 'VER_MIAOS', title: '版本描述', sort: true, width: 300 }
			, { field: 'VER_GENGXSJ', title: '更新时间', sort: true, width: 150 }
			, { field: 'VER_GENGXBLJ', title: '更新包路径', sort: true, width: 150 }
			, { field: 'VER_GENGXRZ', title: '更新日志' }
			, { fixed: 'right', width: 350, title: '操作', align: 'center', toolbar: '#barVersion' }
		]]
		, event:
		{
			onRowdbClick: function (field, row) {
				gridAction.viewRow(row);
			}
		}
	});
	var gridAction = {
		currentEditObj: undefined,
		uploadSuccess: false,
		gridEdit: function (catlog, row, type, arg_readonly) {
			var loadindex;
			var readonly = arg_readonly && arg_readonly != 0 ? 'disabled' : '';
			var uploadFileBtnName = (type == 'edit' && row && row.GENGXSJ && row.GENGXSJ.length > 0 ? "已上传更新包文件" : "上传更新包/参数包文件");
			var updateFileBtnCss = (type == 'edit' && row && row.GENGXSJ && row.GENGXSJ.length > 0 ? ' layui-btn-disabled" disabled' : '"');
			var frm = [
				'<div class="site-block" lay-filter="divgridField"> <form id ="frmGridField" class="layui-form"  action="">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="RWID" class="layui-input">'
				, '			<input type="text" name="WJZY_LEIX" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">所属系统:</label>'
				, '		<div class="layui-form layui-input-block" lay-filter="VER_SUOSXT">'
				, '			<input type="text" name="VER_SUOSXT" disabled lay-verify="required" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">版本:</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="VER_BANB" disabled lay-verify="required" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">版本描述:</label>'
				, '		<div class="layui-input-block">'
				, '			<textarea  name="VER_MIAOS" required class="layui-textarea" disabled></textarea>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">更新时间:</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="VER_GENGXSJ" disabled  class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">更新包路径:</label>'
				, '		<div class="layui-input-block">'
				, '				<input type="text" name="VER_GENGXBLJ" disabled class="layui-input"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<div class="layui-input-block">'
				, '			<div class="layui-upload">'
				, '	  			<button type="button" class="layui-btn' + (readonly == 'disabled' ? ' layui-btn-disabled"' : updateFileBtnCss) + ' id="btnUploadfile" ' + readonly + '>' + uploadFileBtnName + '</button>'
				, '			</div>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">更新日志:</label>'
				, '		<div class="layui-input-block">'
				, '			<textarea  name="VER_GENGXRZ" required class="layui-textarea" disabled style="height: 300px;"></textarea>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '>'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmGridField">保存</button>'
				// , '		  <button type="reset" class="layui-btn layui-btn-primary ' + (type == 'edit' ? 'layui-hide"' : '"') + readonly + '>重置</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
				id: 'coreVersionLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					gridAction.uploadSuccess = false;
					upload.render({
						elem: '#btnUploadfile'
						, accept: 'file' //所有的文件
						, url: layui.cache['contentPath'] + '/manager/version/upload/'
						, data: {}
						, before: function (obj) {
							loadindex = zlContext.showLoading();
						}
						, done: function (res) {
							if (res[statusName] != OK) {
								return layer.msg('上传失败' + res[msgName]);
							}
							else {
								$(res[dataName]).each(function (index, obj) {
									$('#frmGridField input[name=VER_GENGXBLJ]').val(obj["VER_GENGXBLJ"]);
									$('#frmGridField input[name=VER_BANB]').val(obj["VER_BANB"]);
									$('#frmGridField input[name=VER_SUOSXT]').val(obj["VER_SUOSXT"]);
									$('#frmGridField textarea[name=VER_MIAOS]').val(obj["VER_MIAOS"]);
								});
								gridAction.uploadSuccess = true;
							}
							zlContext.closeLoading(loadindex);
						}
						, error: function () {
							layer.msg('上传失败');
							zlContext.closeLoading(loadindex);
						}
					});
					if (type == 'edit') {
						zlContext.autoFill($('#frmGridField'), row);
						$('#frmGridField input[name=EDITTYPE]').val('edit');
						form.render();
					}
					else {
						/**设置隐藏属性*/
						$('#frmGridField input[name=EDITTYPE]').val('new');
						//由于layui是主动刷新需要重新刷新才能显示出状态
						form.render();
						$('#frmGridField input[name=VER_SUOSXT]').change(function () {
							var v = $('#frmGridField input[name=VER_SUOSXT]').val();
							/**设置版本更新信息名 */
							var v1 = zlPinYin.C(v);
							$('#frmGridField input[name=VER_BANB]').val(v1);
							form.render();
						});
					}
					fromlayerIndex = index;
				},
				cancel: function (index, layero) {
					var isDisabled = layero.find('#btnUploadfile').prop("disabled")
					if (!isDisabled && gridAction.uploadSuccess && $('#frmGridField input[name=EDITTYPE]').val() == 'edit') {
						var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
							title: '是否关闭',
							resize: false,
							btn: ['保存关闭', '确定关闭', '取消'], //按钮
							btnAlign: 'c',
							anim: 1,
							icon: 3
						}, function () {
							layer.close(changeConfirmLayer)
							layero.find('[lay-submit]').trigger('click')
						}, function () {
							layer.close(index)
						}, function () {
							layer.close(changeConfirmLayer)
						});
						return false;
					}
					// if (type == 'edit' && readonly != 'disabled') {
					//      zlContext.isFormDataChange('frmGridField',gridAction.currentEditObj.data, gridAction, index)
					//      return false;
					// }
				}
			});
		},
		viewRow: function (row) {

			gridAction.gridEdit(null, row, 'edit', true);
		},
		newRow: function () {
			gridAction.gridEdit(null, null, 'new');
		},
		editRow: function (row) {
			gridAction.gridEdit(null, row, 'edit');
		},
		deleteRows: function (rows, type) {
			if (rows.length == 0) {

				zlContext.warnMsg('请选择需要删除的版本更新信息');
				return;
			}
			//判断是否已更新
			for (var i = 0; i < rows.length; i++) {
				var item = rows[i];
				if (item['VER_GENGXSJ'] && item['VER_GENGXSJ'].length > 0) {
					zlContext.warnMsg('选择项中包含已更新成功的更新包信息，不允许删除');
					return;
				}
			}
			zlContext.confirm('询问', '是否要删除选择的版本更新信息?', function (index) {
				var ids = [];
				for (var i = 0; i < rows.length; i++) {
					ids.push(rows[i]['RWID'])
				}
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/manager/version/remove', { ids: ids.join(',') }, function (result) {
					if (result[statusName] == OK) {
						// gridAction.currentEditObj.del();
						if (type == 'single') {
							gridAction.currentEditObj.del();
							var $pageBox = $('#tbVersion').siblings('div.layui-table-view').find('span.layui-laypage-count'),
								currCount = $pageBox.html().replace(/[^0-9]/ig, "");
							$pageBox.html('共 ' + --currCount + ' 条')
						} else {
							gridAction.refreshGrid('del', null);
						}
						zlContext.successMsg('删除成功');
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		sumbit: function (fields) {
			var editType = $('#frmGridField input[name=EDITTYPE]').val();
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/manager/version/add', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} else if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/manager/version/modify', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, fields);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		search: function () {
			var param = {}
			if ($('#edtSeacherValue').val().length > 0) {
				param['SEARCHVALUE'] = $('#edtSeacherValue').val();
				isloadsearch = true;
			}
			layui.event('WM_USERDEF',
				zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refresh: function (node) {
			$('#edtSeacherValue').val("")
			var param = {}
			if ($('#edtSeacherValue').val().length > 0) {
				param['VER_BANB'] = $('#edtSeacherValue').val();
			}
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
			}
			else {
				// table.reload('tbVersion');
				// gridAction.refresh()
				var addLoading = layer.load();
				versionTb.reload({
					where: {
						'SEARCHVALUE': ''
					},
					page: {
						curr: customCurr
					},
					done: function (res, curr, count) {
						layer.close(addLoading);
						customCurr = curr;
					}
				})
			}
		},
		startUpdate: function (row) {
			//判断是否已经更新
			if (row["VER_GENGXSJ"] && row["VER_GENGXSJ"].length > 0) {
				zlContext.warnMsg("更新包已经更新，无法重复更新");
				return;
			}
			var param = {},
				flag = false;
			zlContext.post(layui.cache['contentPath'] + '/manager/version/startupdate?RWID=' + row['RWID'], param, function (result) {
				if ($('#layer_updateprocesslog .dotting-container').length > 0) {
					$('#layer_updateprocesslog .dotting-container').empty();
				}
				window.setTimeout(function () {
					window.clearInterval(updateProcessTimer);
					$('#layer_updateprocesslog').parent().find('a.layui-layer-btn0').css({
						'border-color': '#1E9FFF',
						'background-color': '#1E9FFF',
						'color': '#fff',
						'cursor': 'pointer'
					})
					flag = true
				}, 2000);
				if (result[statusName] == OK) {
					gridAction.refreshGrid('edit', result[dataName]);
					zlContext.successAlert(result[msgName]);
					return true;
				}
				else {
					zlContext.errorMsg(result[msgName]);
				}
			}, false);
			//进度信息
			var updateProcessContent = [
				'<div>'
				, '	<div class="site-text" id="updateProcessLog" style="padding: 10px 10px 0 10px; line-height: 18px; font-weight: 300;">'
				, '	</div>'
				, '	<div class="site-text dotting-container" style="padding: 0 10px 10px 10px; line-height: 18px; font-weight: 300;">'
				, '		<span>处理中</span><span class="dotting"></span>'
				, '	</div>'
				, '</div>'
			];
			layer.open({
				type: 1
				, title: '执行更新' //不显示标题栏
				, closeBtn: false
				, area: ['80%', '80%']
				, id: 'layer_updateprocesslog' //设定一个id，防止重复弹出
				, btn: '确认关闭'
				, moveType: 1 //拖拽模式，0或者1
				, content: updateProcessContent.join('')
				, success: function (layero, index) {
					layero.find('a.layui-layer-btn0').css({
						'border-color': '#dedede',
						'background-color': '#dedede',
						'color': '#000',
						'cursor': 'not-allowed'
					})
					// processLayerIndex = index;
					isPrvFinish = true;
					window.setTimeout(function () {
						updateProcessTimer = window.setInterval(function () {
							if (isPrvFinish) {
								isPrvFinish = false;
								zlContext.get(layui.cache['contentPath'] + '/manager/version/queryupdateprocess?t=' + Date.parse(new Date()), param, function (result) {
									var $updateProcessLog = layero.find("#updateProcessLog");
									if (OK == result[statusName]) {
										var msgs = result[dataName];
										for (var i = 0; i < msgs.length; i++) {
											$updateProcessLog.append("<span>" + msgs[i].msg + "</span><br>");
										}
									}
								}, false);
								isPrvFinish = true;
							}
						}, 1500);
					}, 200)
				},
				yes: function (index, layero) {
					if (flag) {
						layer.close(index)
					}
					gridAction.refresh(null);
					return false;
				}
			});
		},
		download: function (row) {
			loadingLayer = layer.msg('下载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
			var _downloadid = new Date().getTime();
			var url = layui.cache['contentPath'] + '/manager/version/download?id=' + row['RWID'] + '&_downloadid=' + _downloadid;
			if ($("#ifdownload").length == 0) {
				$("body").append('<iframe id=ifdownload style="display:none"></iframe>');
			}
			$("#ifdownload").attr("src", url);
			var iframe = document.getElementById('ifdownload');
			iframe.onload = iframe.onreadystatechange = function iframeload() {
				if (intervalId) {
					clearInterval(intervalId);
				}
				layer.close(loadingLayer);
				if (!iframe.readyState || iframe.readyState == "complete") {
					var iframeText = document.getElementById('ifdownload').contentWindow.document;
					iframeText = $(iframeText).text();
					if (iframeText) {
						var obj = JSON.parse(iframeText);
						zlContext.errorMsg(obj.msg);
					}

				}
			};
			intervalId = setInterval(function () {
				var cookieName = '_downloadid' + _downloadid;
				var cookieValue = zlContext.getCookieValue(cookieName);
				if (cookieValue && cookieValue == _downloadid) {
					layer.close(loadingLayer);
					if (intervalId) {
						clearInterval(intervalId);
						intervalId = undefined;
					}
				}
			}, 500);
		}
	}
	// $('#btnSeacher').on('click', function () {
	// 	customCurr = 1;
	// 	gridAction.search();
	// });
	$('.zl-container').on('keyup', '#edtSeacherValue', function (event) {
		var keyCode = event.keyCode;
		customCurr = 1;
		$('.zl-container').attr('data-search', $(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
	});

	//头工具栏事件
	table.on('toolbar(tbVersion)', function (obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'addVersion':
				gridAction.newRow();
				break;
			case 'deleteVersion':
				var rows = checkStatus.data;
				gridAction.deleteRows(rows, 'multi');
				break;
			case 'refreshVersion':
				gridAction.refresh(null);
				break;
		}
	});
	//监听行工具事件
	table.on('tool(tbVersion)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			gridAction.deleteRows([row], 'single');
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		} else if (layEvent === 'execute') { //更新
			gridAction.currentEditObj = obj;
			gridAction.startUpdate(row);
		} else if (layEvent === 'download') { //下载
			gridAction.currentEditObj = obj;
			gridAction.download(row);
		}


	});
	//提交
	form.on('submit(frmGridField)', function (frm) {
		return gridAction.sumbit(frm.field);
	});
	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		var index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
		var loadGridData = function (tableId, url, param) {
			versionTb.reload({
				url: url
				, height: fullheight
				// , page: true
				, method: 'post'
				, page: {
					curr: customCurr
				}
				, where: param
				, done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(index);
					customCurr = curr;
				}
			});
		}
		//刷新
		loadGridData('tbVersion', layui.cache['contentPath'] + '/manager/version/query', param);
	});
	// gridAction.refresh(null);

	$(window).on('resize', function () {
		//控制高度的设置
		setMaxHeihgt(16, 32);
	}).resize();
	//控制高度的设置
	function setMaxHeihgt(deff, deff1) {
		$('.docking-left').height($(window).height() - deff);
		$('.docking-fill').height($(window).height() - deff);
		var treeHeaderH = $('.zltree-header').height();
		$('.layui-card-body').height($(window).height() - deff1);
		$('.zltree-body').height($('.layui-card-body').height() - treeHeaderH - 20);
	}
});